package com.youlai.netty.service.tcp.client;

import com.youlai.netty.service.tcp.BootNettyChannelInitializer;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.net.NioEndpoint;

import java.util.concurrent.TimeUnit;

/**
 * 创建一个TCP客户端
 * @author zc
 * @date 2023-02-04 17:00
 */
@Slf4j
public class TCPClient {

    public void connect(String host,int port){
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(new NioEventLoopGroup())                 //线程模型
                .channel(NioSocketChannel.class)              //指定IO模型为NIO模型
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS,5000)    //连接超时时间
                .option(ChannelOption.SO_KEEPALIVE,true)     // 开启心跳机制
                .option(ChannelOption.TCP_NODELAY,true)     // 开启Nagle算法,即有数据就发送
                .handler(new BootNettyChannelInitializer<SocketChannel>());

        //开始连接
        ChannelFuture future = bootstrap.connect(host, port);
        future.addListener(future1 -> {
           if(future1.isSuccess()){
                      log.info("连接ip:{},端口:{}成功",host,port);
           }else{
               log.warn("连接失败:{}",future1.cause().getMessage());
               //添加失败重连,每隔5秒重连一次
               EventLoopGroup eventLoopGroup = bootstrap.config().group();
               eventLoopGroup.schedule(new Runnable() {
                   @Override
                   public void run() {
                       connect(host,port);
                   }
               }, 5, TimeUnit.SECONDS);
           }
        });
    }


}
